<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
// import Joomla controlleradmin library
jimport('joomla.application.component.controlleradmin');
 
/**
* Categorys Controller
 */
class ShopControllerCategories extends JControllerAdmin
{
	/**
	 * Proxy for getModel.
	 * @since	1.6
	 */
	public function getModel($name = 'Category', $prefix = 'ShopModel') 
	{
		$model = parent::getModel($name, $prefix, array('ignore_request' => true));
		return $model;
	}
	/**
	* Add category
	**/
	public function add()
	{
		$this->setRedirect('index.php?option=com_shop&view=categories&layout=add');
	}
	/**
	* Edit category 
	**/
	/* public function edit()
	{
		$this->setRedirect('index.php?option=com_shop&view=category&layout=edit');
	} */
	/**
	*	Save category
	**/
	public function save()
	{
		$db =& JFactory::getDBO();
			
		JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . '/tables');
		$row = JTable::getInstance('Category','ShopTable');
		$row->bind(JRequest::get('post'));
		
		// check not row in database
		$title = JRequest::getVar('title','');
		$alias = JRequest::getVar('alias','');
		$parent_id = JRequest::getVar('parent_id', null);
		$db->setQuery("select * from #__shop_category where title = '$title'");
		$ro = $db->loadObject();
		if(!count($ro)){
			if($parent_id === ''){
			
				$query = "select * from #__shop_category order by rgt desc limit 1";
				$db->setQuery($query);
				$aro = $db->loadObject();
				if(!count($aro))
					$right = 0;
				else
					$right = $aro->rgt;
					
				$row->lft = $right +1;
				$row->rgt = $right + 2;
				$row->parent_id = 0;
				$row->level = 1;
				$row->ordering = 1;
				
				// Set alias
				$alias = JApplication::stringURLSafe($alias);
				if (empty($alias)) {
					$alias = JApplication::stringURLSafe($title);
				}
				$row->alias = $alias;
				$description = JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW );
				$row->description = $description;
				
				include  JPATH_COMPONENT_ADMINISTRATOR . DS . "class.upload.php";
				$img_path = JPATH_SITE . DS . 'images' . DS . 'image_category' .DS;
				
				$img = new Upload($_FILES['upload_file']);
				$new_img_name = $this->name_id_element($alias);
				
				
				if ($img->uploaded) {	  					
					//--- upload image origin
					$img->image_convert = 'jpg';
		            $img->file_new_name_body = $new_img_name;
		            $img->Process($img_path);
					
					// resize image thumb
					$img->file_new_name_body = $new_img_name;
					$img->image_resize = true;
					$img->image_convert = 'jpg';
					$img->image_x = 160;
					$img->image_ratio_y = true;
					$img->Process($img_path.'thumb'.DS);
					if ($img->processed) {
						$row->image = $new_img_name.'.jpg';
					}
				}
			 	if (!$row->store()) {
					echo  "<script>alert({$row->getError()});window.history.go(-1)</script>\n";
				}
				$this->setMessage(JText::_('COM_SHOP_SAVE_SUCCESS'));
				$this->setRedirect('index.php?option=com_shop&view=categories');
			}
			else
			{
				// insert node chile of parent
				$query = "select * from #__shop_category where id = $parent_id";
				$db->setQuery($query);
				$pr = $db->loadObject();
				if(count($pr) === 0){
					$this->setMessage(JText::_('COM_SHOP_ERROR_NOT_FOUND_PARENT'));
					$this->setRedirect('index.php?option=com_shop&view=categories');
				}
				else
				{
					$left = $pr->lft;
					
					$db = JFactory::getDBO();
					$query = $db->getQuery(true);
					$query->update('#__shop_category');
					$query->set('rgt = rgt + 2');
					$query->where('rgt > '.$left );
					$db->setQuery((string)$query);
					$db->query();
					
					$query->clear();
					$query->update('#__shop_category');
					$query->set('lft = lft + 2');
					$query->where('lft > '.$left );
					$db->setQuery((string)$query);
					$db->query();
					
					//-- insert record in database----
					//begin insert 
						$row->lft = $left +1;
						$row->rgt = $left + 2;
						$row->parent_id = $pr->id;
						$row->level = $pr->level + 1;
						$row->ordering = 1;
						
						// Set alias
						$alias = JApplication::stringURLSafe($alias);
						if (empty($alias)) {
							$alias = JApplication::stringURLSafe($title);
						}
						$row->alias = $alias;
						$description = JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW );
						$row->description = $description;
						
						include  JPATH_COMPONENT_ADMINISTRATOR . DS . "class.upload.php";
						$img_path = JPATH_SITE . DS . 'images' . DS . 'image_category' .DS;
						
						$img = new Upload($_FILES['upload_file']);
						$new_img_name = $this->name_id_element($alias);
						
						
						if ($img->uploaded) {	  					
							//--- upload image origin
							$img->image_convert = 'jpg';
							$img->file_new_name_body = $new_img_name;
							$img->Process($img_path);
							
							// resize image thumb
							$img->file_new_name_body = $new_img_name;
							$img->image_resize = true;
							$img->image_convert = 'jpg';
							$img->image_x = 160;
							$img->image_ratio_y = true;
							$img->Process($img_path.'thumb'.DS);
							if ($img->processed) {
								$row->image = $new_img_name.'.jpg';
							}
						}
						if (!$row->store()) {
							echo  "<script>alert({$row->getError()});window.history.go(-1)</script>\n";
						}
						$this->setMessage(JText::_('COM_SHOP_SAVE_SUCCESS'));
						$this->setRedirect('index.php?option=com_shop&view=categories');
							//end insert
			
				}

			}
		}
		else
		{
			// da ton tai danh muc nay roi
			$this->setMessage(JText::_('COM_SHOP_TITLE_EXISTS'));
			$this->setRedirect('index.php?option=com_shop&view=categories');
		}
		

//	$this->setMessage(JText::_('COM_SHOP_SAVE_SUCESS'));
	//	$this->setRedirect('index.php?option=com_shop&view=category');
	}
	/**
	* Cancel save or new
	**/
	public function cancel()
	{
		$this->setRedirect('index.php?option=com_shop&view=categories');
	}
	/***
	* Check disable home page category
	*
	**/
	public function unhome()
	{
		$cid = JRequest::getVar('cid');
		$id = intval($cid[0]);
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->update('#__shop_category');
		$query->set('home = 0');
		$query->where('id = '.$id );
		$db->setQuery((string)$query);
		$db->query();
		$this->setMessage(JText::_('COM_SHOP_HOME_DISABLE_SUCCESS'));
		$this->setRedirect('index.php?option=com_shop&view=categories');
	}
	/***
	* Check disable home page category
	*
	**/
	public function home()
	{
		$cid = JRequest::getVar('cid');
		$id = intval($cid[0]);
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->update('#__shop_category');
		$query->set('home = 1');
		$query->where('id = '.$id );
		$db->setQuery((string)$query);
		$db->query();
		$this->setMessage(JText::_('COM_SHOP_HOME_ENABLE_SUCCESS'));
		$this->setRedirect('index.php?option=com_shop&view=categories');
	}
	/**
	* function get element extention name for image
	*/
	public function name_id_element($string = null) {
    	$string = trim($string);
    	$string = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $string);
    	$string = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $string);
    	$string = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $string);
    	$string = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $string);
    	$string = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $string);
    	$string = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $string);
    	$string = preg_replace("/(đ)/", 'd', $string);

    	$string = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $string);
    	$string = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $string);
    	$string = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $string);
    	$string = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $string);
    	$string = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $string);
    	$string = preg_replace("/(\'|\")/", '', $string);
    	$string = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $string);
    	$string = preg_replace("/(Đ)/", 'D', $string);
    	$string = str_replace("--", '_', $string);
    	$string = str_replace("--", '_', $string);
    	$string = str_replace("--", '_', $string);
        $string = str_replace("-", '_', $string);

        $string = str_replace(" ", '_', $string);
         $string = str_replace("/", '_', $string);
    	return $string;
    }
	/**
	*	Call published
	*
	***/
	function publish()
	{
		 // Get items to publish from the request.
		$cid    = JRequest::getVar('cid', array(), '', 'array');
		$data    = array('publish' => 1, 'unpublish' => 0, 'archive'=> 2, 'trash' => -2, 'report'=>-3);
		  $task     = $this->getTask();
		  $value    = JArrayHelper::getValue($data, $task, 0, 'int');
		 if (empty($cid)) {
			 JError::raiseWarning(500, JText::_($this->text_prefix.'_NO_ITEM_SELECTED'));
		}
		else
		{
		
				$db = JFactory::getDBO();
				$query = $db->getQuery(true);
				$query->select('*');
				$query->from('#__shop_category');
				$query->where('id = '.intval($cid[0]));
				$db->setQuery((string)$query);
				$row = $db->loadObject();
				
				$query->clear();
				$query->update('#__shop_category');
				$query->set('state = '.$value);
				$query->where('lft >= '.$row->lft);
				$query->where('rgt <= '.$row->rgt);
				$db->setQuery((string)$query);
				//$db->query();
			 // Publish the items.
             if (!$db->query()) {
                  JError::raiseWarning(500, 'COM_SHOP_PUBLISHED_ERROR');
              }
              else {
                  if ($value == 1) {
                      $ntext = $this->text_prefix.'_N_ITEMS_PUBLISHED';
                  }
                  else if ($value == 0) {
                      $ntext = $this->text_prefix.'_N_ITEMS_UNPUBLISHED';
                  }
                  else if ($value == 2) {
                      $ntext = $this->text_prefix.'_N_ITEMS_ARCHIVED';
                  }
                 else {
                     $ntext = $this->text_prefix.'_N_ITEMS_TRASHED';
                  }
                  $this->setMessage(JText::plural($ntext, count($cid)));
             }
		}
		$this->setRedirect('index.php?option=com_shop&view=categories');
		
	}
	function delete()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit(JText::_('JInvalid_Token'));
		// Initialise variables.
		$ids	= JRequest::getVar('cid', array(), '', 'array');
		$ids = implode(',',$ids);
		$db =& JFactory::getDBO();
		//---------- get sub category
		$query = "select * from #__shop_category where parent_id in ( $ids ) ";
		$db->setQuery($query);
		$sub = $db->loadObjectList();
		if(count($sub) == 0){
			$query = $db->getQuery(true);
			$query->select('*');
			$query->from('#__shop_category');
			$query->where("id in ($ids)");
			$db->setQuery((string)$query);
			$rows = $db->loadObjectList();
			foreach($rows as $row){
				$right = $row->rgt;
						$query->clear();
						$query->update('#__shop_category');
						$query->set('rgt = rgt - 2');
						$query->where('rgt > '.$right );
						$db->setQuery((string)$query);
						$db->query();
						
						$query->clear();
						$query->update('#__shop_category');
						$query->set('lft = lft - 2');
						$query->where('lft > '.$right );
						$db->setQuery((string)$query);
						$db->query();
						
						$query->clear();
						$query->delete('#__shop_category');
						$query->where("id = $row->id");
						$db->setQuery($query);
						$db->query();
						$img_path = JPATH_SITE . DS . 'images' . DS . 'image_category' .DS;
						$this->deleteFile($img_path,$row->image);
						$this->deleteFile($img_path.'thumb'.DS,$row->image);
			}
			$this->setMessage(JText::_('SHOP_CATEGORY_DELETE_SUCCESS').$ids);
			$this->setRedirect('index.php?option=com_shop&view=categories');
		}
		else
		{
			$this->setMessage(JText::_('SHOP_CATEGORY_DELETE_ERROR_SUB').$ids);
			$this->setRedirect('index.php?option=com_shop&view=categories');
		}
		
	}
	/**
	*
	*
	*	delete file on directory
	*/
	function deleteFile($path, $filename){
		$upfile = $path . $filename;
		if (file_exists($upfile)){
			unlink($upfile);
		}
	}
	/**
	*
	*	Save order
	***/	
	function saveorder()
	{
		JRequest::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
		 return parent::saveorder();
	}
}